import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';

Reducer<WebViewComponentState> buildReducer() {
  return asReducer(
    <Object, Reducer<WebViewComponentState>>{
      WebViewComponentAction.onWebViewCreate: onWebViewCreate,
      WebViewComponentAction.onPageFinish: _onPageFinish,
      WebViewComponentAction.onRequestUrl: _onRequestUrl,
      WebViewComponentAction.onRefresh: _onRefresh,
    },
  );
}

WebViewComponentState onWebViewCreate(
    WebViewComponentState state, Action action) {
  final WebViewComponentState newState = state.clone()
    ..webViewController = action.payload;
  if (state.url.length > 0) {
    newState.webViewController.loadUrl(state.url);
    print('webview_flutter loadUrl:${state.url}');
  }
  return newState;
}

WebViewComponentState _onPageFinish(
    WebViewComponentState state, Action action) {
  final WebViewComponentState newState = state.clone();
  newState.isLoad = true;
  newState.requestLoad = false;
  return newState;
}

WebViewComponentState _onRequestUrl(
    WebViewComponentState state, Action action) {
  final WebViewComponentState newState = state.clone();
  newState.isLoad = false;
  newState.requestLoad = false;
  newState.webViewController.loadUrl(newState.url);
  print('webview_flutter RequestUrl:${state.url}');
  return newState;
}

WebViewComponentState _onRefresh(WebViewComponentState state, Action action) {
  final WebViewComponentState newState = state.clone();
  newState.requestLoad = false;
  newState.webViewController.reload();
  return newState;
}
